part of base_package;

class FileUtil {
  /// 获取APP下文件路径
  /// Android:  getFilesDir
  /// iOS:  NSApplicationSupportDirectory
  static Future<String> getFilesDir() async {
    Directory filesDir = await getApplicationSupportDirectory();
    return filesDir.path;
  }

  /// 获取APP下缓存路径
  /// Android:  NSCachesDirectory
  /// iOS:  getCacheDir
  static Future<String> getCacheDir() async {
    Directory cacheDir = await getTemporaryDirectory();
    return cacheDir.path;
  }

  /// 保存图片和视频到相册中
  /// Android：
  ///     在 AndroidManifest.xml 文件中添加
  ///     <application android:requestLegacyExternalStorage="true" .....>
  ///     获取存储权限storage
  ///
  /// iOS：
  ///     在 Info.plist 文件中添加
  ///     <key>NSPhotoLibraryAddUsageDescription</key>
  ///     <string>请求添加图片到相册</string>
  ///     获取写入相册权限photosAddOnly
  ///
  /// 权限申请详情，请查看：permission_util.dart 文件
  static saveImgOrVideoToGallery(filePath,
      {bool isDelSourceFile = false}) async {
    await ImageGallerySaver.saveFile(filePath);
    if (isDelSourceFile) {
      File(filePath).delete();
    }
  }

  /// 获取文件名字，包括后缀
  static String getFileName(String filePath) {
    return filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length);
  }

  /// 获取文件名后缀
  static String getFileSuffix(String filePath) {
    return filePath.substring(filePath.lastIndexOf('.') + 1, filePath.length);
  }

  static List<String> diyCameraList = [];

  /// 从相册或者相机获取图片和视频
  /// type : 0、相机图片，1、相册图片，2、相机视频，3、相册视频
  static Future<PickedFile?> getImageOrVideo(BuildContext context, int type,
      {int imageQuality = 70, double? maxWidth, double? maxHeight}) async {
    final deviceInfoPlugin = DeviceInfoPlugin();
    final deviceInfo = await deviceInfoPlugin.deviceInfo;
    final map = deviceInfo.toMap();
    switch (type) {
      case 0:
        if (diyCameraList.contains(map['androidId'])) {
          String? path = await CameraUtil.openCamera(
              context, imageQuality, maxWidth, maxHeight);
          return path == null ? null : PickedFile(path);
        } else {
          return ImagePicker()
              .getImage(source: ImageSource.camera, imageQuality: imageQuality);
        }
      case 1:
        return ImagePicker()
            .getImage(source: ImageSource.gallery, imageQuality: imageQuality);
      case 2:
        return ImagePicker().getVideo(source: ImageSource.camera);
      case 3:
        return ImagePicker().getVideo(source: ImageSource.gallery);
      default:
        return Future.value(null);
    }
  }

  /// Uint8List转图片文件
  static Future<String> uint8List2File(Uint8List imageByte) async {
    String dirPath = await getCacheDir();
    //生成file文件格式
    var file =
        await File('$dirPath/image_${DateTime.now().millisecond}.png').create();
    //转成file文件
    file.writeAsBytesSync(imageByte);
    return file.path;
  }
}
